﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebServiceTMS.Helpers;

namespace WebServiceTMS.Controllers
{
    public class TeamController : ApiController
    {
        //GET api/Team/GetAllUserTeams
        [HttpGet]
        [ActionName("GetAllUserTeams")]
        public HttpResponseMessage GetAllUserTeams(HttpRequestMessage request)
        {
            return ReturnTeams(false, request);
        }

        //GET api/Team/GetAllTeams
        [HttpGet]
        [ActionName("GetAllTeams")]
        public HttpResponseMessage GetAllTeams(HttpRequestMessage request)
        {
            return ReturnTeams(true, request);
        }

        private HttpResponseMessage ReturnTeams(bool allTeams, HttpRequestMessage request)
        {
            try
            {
                var query = request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
                if (query.Count > 0)
                {
                    string userId = null;
                    bool isSuccessUserId = query.TryGetValue("userId", out userId);
                    userId = TMSCryptography.Decrypt(userId);
                    if (isSuccessUserId)
                    {
                        int userIdNumeric;
                        bool isUserIdANumber = int.TryParse(userId, out userIdNumeric);
                        if (isUserIdANumber)
                        {
                            if (allTeams)
                            {
                                return TeamHelper.GetAllTeamsHelper(userIdNumeric);
                            }
                            return TeamHelper.GetAllUserTeamsHelper(userIdNumeric);
                        }
                        return HttpResponseHelper.CreateHttpResponse("error", "Parameter error");
                    }
                    return HttpResponseHelper.CreateHttpResponse("error", "Some parameters are empty!");
                }
                return HttpResponseHelper.CreateHttpResponse("error", "Parameters list is empty");
            }
            catch (Exception ex)
            {
                return HttpResponseHelper.CreateHttpResponse("server_error", ex.Message);
            }
        }
    }
}
